package tk.jfree.example.gridfs.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author Cheng.Wei
 * @date 2019/09/23 14:01
 */
@Service
public class FileServiceImpl implements FileService{

    @Autowired private GridFsTemplate gridFsTemplate;

    @Autowired private GridFSBucket gridFSBucket;

    @Override
    public ObjectId save(MultipartFile file) throws IOException {
        // 获得文件类型
        String contentType = file.getContentType();
        return gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), contentType);
    }

    @Override
    public GridFsResource get(String id) {
        GridFSFile result = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        return convertGridFSFile2Resource(result);
    }

    public GridFsResource convertGridFSFile2Resource(GridFSFile gridFsFile) {
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());
        return new GridFsResource(gridFsFile, gridFSDownloadStream);
    }


    @Override
    public void delete(String id) {
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(id)));
    }
}
